﻿using System;
using System.ComponentModel;
using Loki;
using Loki.UI;
using Loki.UI.Win;
using Luna.UI.Accounting;

namespace Luna.UI.Win.Accounting
{
    /// <summary>
    /// Account list view.
    /// </summary>
    public partial class AccountListView : LunaView, IView<AccountListViewModel>
    {
        public AccountListView()
        {
            BindNameOnVMState = false;
            InitializeComponent();
            this.BindingChanged += AccountListView_BindingChanged;
        }

        private void AccountListView_BindingChanged(object P_Sender, EventArgs e)
        {
            VIEW_Accounts.Configure(ViewModel.Accounts);

            VIEW_Accounts.FocusedRowChanged += new DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventHandler(VIEW_Accounts_FocusedRowChanged);
            this.WatchChange(ViewModel, v => v.SelectedAccountIndex, v => v.ViewModel_SelectedAccountIndex_Changed);
        }

        private void ViewModel_SelectedAccountIndex_Changed(object P_Sender, PropertyChangedEventArgs e)
        {
            VIEW_Accounts.FocusedRowHandle = (int)ConverterHelper.HandleToIndex.Convert(ViewModel.SelectedAccountIndex, typeof(int), VIEW_Accounts, UIContext.Culture);
        }

        private void VIEW_Accounts_FocusedRowChanged(object P_Sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            ViewModel.SelectedAccountIndex = (int)ConverterHelper.HandleToIndex.ConvertBack(VIEW_Accounts.FocusedRowHandle, typeof(int), VIEW_Accounts, UIContext.Culture);
        }

        public new AccountListViewModel ViewModel
        {
            get { return (AccountListViewModel)base.ViewModel; }
            set { base.ViewModel = value; }
        }

        private void BAI_Add_ItemClick(object P_Sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ViewModel.Add.Execute(null);
        }

        private void GRD_Accounts_DoubleClick(object P_Sender, EventArgs e)
        {
            if (VIEW_Accounts.IsValidRowHandle(VIEW_Accounts.FocusedRowHandle))
            {
                ViewModel.Open.Execute(null);
            }
        }
    }
}